package com.pansky.crm.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pansky.crm.entity.Employee;
import com.pansky.crm.entity.Privilege;
import com.pansky.crm.entity.vo.EmployeeInfo;
import com.pansky.crm.service.EmployeeService;
import com.pansky.crm.service.PrivilegeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义Realm 处理登录 权限
 * 
 * @author numberone
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private PrivilegeService privilegeService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("============用户授权==============");
        //获取到前端传输用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //使用用户名查询该用户的权限
        Employee employee = new Employee();
        employee.setLoginName(username);
        List<EmployeeInfo> employeeInfos = employeeService.findEmployeeInfo(employee);
        //声明set进行去重
        Set<String> set=new HashSet<>();
        if (CollectionUtils.isNotEmpty(employeeInfos)) {
            EmployeeInfo employeeInfo = employeeInfos.get(0);
            List<Privilege> privileges = privilegeService.findPrivilegeByRoleId(employeeInfo.getRole().getId());
            privileges.forEach(privilege -> set.add(privilege.getUrl()));
        } else {
            log.error("doGetAuthorizationInfo fail. employeeInfos is null!");
        }
        log.info("set is {}", set);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("============用户验证==============");
        //从token中获取信息,此token只是shiro用于身份验证的,并非前端传过来的token.
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", username);
        Employee employee = employeeService.getOne(wrapper);
        String password = null;
        if (null != employee) {
            password = employee.getLoginPwd();
        }
        if (null == password) {
            throw new AuthenticationException("doGetAuthenticationInfo中的用户名不对");
        } else if (!password.equals(new String(token.getPassword()))){
            throw new AuthenticationException("doGetAuthenticationInfo中的密码不对");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(),password,getName());
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo()
    {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}
